<template>
  <el-dialog
    :modal="false"
    title="拍摄照片"
    class="gl_dialog_TitleLine gl_dl_footer"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :append-to-body="true"
    :before-close="stopNavigator"
    width="540px"
    top="25vh"
  >
    <div :loading="loading" style="width:100%;height:100%">
      <video v-if="flag" id="videoCamera" width="500" height="300" autoplay />
      <div v-else style="text-align: center;">
        <img class="image" :src="imgSrc">
      </div>
      <canvas id="canvasCamera" style="display:none;" width="300" height="300" />
      <div class="info">
        <div>
          <span class="title">学员姓名</span>
          <span>{{ info.name }}</span>
        </div>
        <div>
          <span class="title">证件号码</span>
          <span>{{ info.idCardNumber }}</span>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="stopNavigator()">关闭摄像头</el-button>
      <el-button :loading="btnLoading" @click="setImage()">采集</el-button>
    </span>
  </el-dialog>

</template>
<script>
import axios from 'axios';
import { api_PUT_ClubFace } from '@/extend/api/hallswaggerApi/app.js';
import { UpdateFaceInput } from '@/lib/form/hall/swaggerForm';
export default {
  data() {
    return {
      collectQO: new UpdateFaceInput(),
      info: {
        name: '',
        idCardNumber: ''
      },
      flag: true,
      loading: false,
      dialogVisible: false,
      thisCancas: null,
      thisContext: null,
      thisVideo: null,
      imgSrc: '', // 图片拍照
      file: null,
      action: `${WEB_CONFIG.VUE_APP_STATIC_FILE_RUL}/api/upload/image`, // 图片上传地址
      btnLoading: false
    };
  },
  methods: {
    // 打开摄像头
    collect() {
      var _this = this;
      this.$nextTick(function() {
        this.thisCancas = document.getElementById('canvasCamera');
        this.thisContext = this.thisCancas.getContext('2d');
        this.thisVideo = document.getElementById('videoCamera');

        if (navigator.mediaDevices === undefined) {
          navigator.mediaDevices = {};
        }
        if (navigator.mediaDevices.getUserMedia === undefined) {
          navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
            var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
              return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
            }
            // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
              getUserMedia.call(navigator, constraints, resolve, reject);
            });
          };
        }
        var constraints = { audio: false, video: { width: 300, height: 300, transform: 'scaleX(-1)' }};
        navigator.mediaDevices.getUserMedia(constraints).then(function (stream) {
        // 旧的浏览器可能没有srcObject
          if ('srcObject' in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
          // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        }).catch(err => {
          console.log(err);
        });
      });
    },
    // 拍照 绘制图片（拍照功能）
    setImage () {
      var _this = this;
      // 点击，canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, 300, 300);
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL('image/png');
      this.imgSrc = image;
      this.collectQO.base64Image = image.split(',')[1];
      this.btnLoading = true;
      this.flag = false;
      api_PUT_ClubFace(this.collectQO).then(res => {
        this.btnLoading = false;
        this.flag = true;
        this.dialogVisible = false;
        this.imgSrc = '';
        this.$message({ type: 'success', message: '采集成功！' });
        this.thisVideo.srcObject.getTracks()[0].stop();
        this.$emit('refresh', 1);
      }, error => {
        this.imgSrc = '';
        this.flag = true;
        _this.thisVideo.srcObject.getTracks()[0].stop();
        _this.collect();
        this.btnLoading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // base64转文件
    dataURLtoFile (dataurl, filename) {
      var arr = dataurl.split(',');
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    // 图片上传
    upload() {
      this.file = this.dataURLtoFile(this.imgSrc, 'touxiang.png');
      if (!this.file) reject(new Error());
      const form = new FormData();
      form.append('formFile', this.file);
      this.uploadApi(this.action, form).then(res => {
        if (res.status === 200) {
          console.log(res);
        }
      });
    },
    uploadApi(url, file) {
      const config = {
        headers: {
          Authorization: 'Bearer ' + this.tokenInfo
        }
      };
      return axios.post(url, file, config);
    },
    stopNavigator() {
      this.thisVideo.srcObject.getTracks()[0].stop();
      this.dialogVisible = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.info {
  padding: 0px 100px 0px 100px;
  line-height: 42px;
  font-size: 14px;
  .title {
    font-weight: bold;
    margin-right: 10px;
  }
}
.image {
  width: 300px;
  height: 300px;
  margin: 0px;
  padding: 0px;
}
</style>
